package org.kardigen.lg.entity;

import java.util.List;

import javax.jdo.FetchPlan;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Version;
import javax.jdo.annotations.VersionStrategy;
import javax.jdo.identity.StringIdentity;

import org.kardigen.lg.service.server.PMF;

@PersistenceCapable(detachable = "true")
@Version(strategy = VersionStrategy.VERSION_NUMBER, column = "VERSION", extensions = { @Extension(vendorName = "jpox", key = "field-name", value = "version") })
public class Training {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
	private String id;

	@Persistent
	private String trainingName;

	@Persistent
	private List<TrainingChapter> chapters;

	private Long version;

	public static Training findTraining(String id) {
		if (id == null) {
			return null;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();

		try {
			tx.begin();
			pm.getFetchPlan().addGroup(FetchPlan.ALL);
//			pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
//			pm.setDetachAllOnCommit(true);
			Class<Training> clazz = Training.class;
			StringIdentity stringIdentity = new StringIdentity(clazz, id);
			Object object = pm.getObjectById(stringIdentity);
			tx.commit();
			return clazz.cast(object);
		} catch (Exception e) {
			tx.rollback();
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}
	}

	public void setChapters(List<TrainingChapter> chapters) {
		this.chapters = chapters;
	}

	public List<TrainingChapter> getChapters() {
		return chapters;
	}

	public void setTrainingName(String trainingName) {
	   this.trainingName = trainingName;
   }

	public String getTrainingName() {
	   return trainingName;
   }

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setVersion(Long version) {
	   this.version = version;
   }

	public Long getVersion() {
	   return version;
   }
}
